<template>
  <div class="bg-white flex flex-col">
    <div class="w-[350px] m-auto flex flex-col md:w-[1440px] md:m-auto">
      <!-- Banner区域 -->
      <div class="relative w-full h-[600px] bg-gradient-to-r from-gray-800 to-gray-900 overflow-hidden">
        <!-- 背景图片 -->
        <div class="absolute inset-0">
          <img
            :src="currentBannerImage"
            class="w-full h-full object-cover cursor-pointer"
            @click="goToBannerDetail"
          />
        </div>
        
        <!-- 新闻描述区域 - 悬浮在底部 -->
        <div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-75 h-[200px] z-10">
          <!-- 左右导航按钮 - 水平靠上对齐 -->
          <div v-if="bannerCases.length > 1" class="absolute top-10 right-[30%] flex space-x-8 z-20">
            <!-- 左导航按钮 -->
            <button @click="changeBannerIndex(-1)" class="cursor-pointer">
              <img src="@/assets/images/arrow-right-grey.png" class="w-[37px] h-[37px] transform rotate-180">
            </button>
            <!-- 右导航按钮 -->
            <button @click="changeBannerIndex(1)" class="cursor-pointer">
              <img src="@/assets/images/arrow-right-grey.png" class="w-[37px] h-[37px]">
            </button>
          </div>
          
          <div class="absolute bottom-0 left-0 right-0 px-12 py-6">
            <div class="flex justify-between items-center mb-4">
              <!-- 左侧：案例描述 -->
              <div class="flex flex-col max-w-[60%]">
                <h1 class="text-[35px] md:text-[35px] font-bold leading-tight text-white mb-2">
                  {{ currentCase.title }}
                </h1>
                <div class="text-white text-[24px]">{{ currentCase.summary }}</div>
              </div>
              
              <div class="flex items-center flex-2 mr-20 text-white text-[24px]">
                <!-- 日期 -->
                {{ formatDate(currentCase.createAt) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 案例列表 -->
      <div class="w-[90%] m-auto flex justify-between items-center mt-8">
        <span class="text-[44px] text-primary font-bold">Cases List</span> 
        <span class="flex flex-1 justify-end">
          <img src="@/assets/images/line.png" class="w-[95%]">
        </span>
      </div>

      <div v-for="(item, index) in caseList" :key="index" class="m-auto w-full max-w-[1200px]"> <!-- 添加最大宽度和宽度100% -->
        <SidedLayout
          type="case"
          :title="item.title" 
          :desc="item.summary" 
          :bgImg="item.coverImage" 
          :date="item.createAt"
          :cid="item.cid"
        />
      </div>
      <div class="m-auto w-[45%] flex justify-between items-center pb-[30px]">
        <!-- 左翻页按钮 -->
        <button
          @click="handlePrevPage"
          :disabled="currentPage <= 1"
          :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': currentPage <= 1 }
            ]">
          <img class="w-[50px] h-[50px]" src="@/assets/images/previous.png" />
        </button>
        
        <!-- 右翻页按钮 -->
        <button
          @click="handleNextPage"
          :disabled="currentPage >= totalPages"
          :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': currentPage >= totalPages }
            ]">
          <img class="w-[50px] h-[50px]" src="@/assets/images/next.png" />
        </button>
      </div>
    </div>
    <!-- <FooterBg /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import SidedLayout from '@/components/SidedLayout.vue'
import { contentDetailApi, contentListApi } from '@/api/content'
import { formatDate } from '@/utils/tool'
import { useRouter } from 'vue-router'
const router = useRouter()

// Banner轮播数据
const bannerCases = ref([] as any[])

const currentBannerIndex = ref(0)

// 计算当前显示的新闻和图片
const currentCase = computed(() => bannerCases.value[currentBannerIndex.value] || {})
const currentBannerImage = computed(() => {
  const cases: any = bannerCases.value[currentBannerIndex.value]
  return cases ? cases.coverImage : ''
})

// 自动轮播
let autoPlayTimer: NodeJS.Timeout

// 案例列表
const caseList = ref([] as any[])

// 案例当前页码
const currentPage = ref(1)

// 案例总页数
const totalPages = ref(0)

const startAutoPlay = () => {
  autoPlayTimer = setInterval(() => {
    currentBannerIndex.value = (currentBannerIndex.value + 1) % bannerCases.value.length
  }, 5000) // 5秒切换一次
}

const stopAutoPlay = () => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer)
  }
}

const getBannerCases = async () => {
  bannerCases.value = []
  let query = {
    recommend: true,
    category: 'case',
    status: 'publish',
    page: 1,
    limit: 5
  }
  try {
    const res: any = await contentListApi(query)
    if (res.code === 0 && res.data && res.data.list) {
      let promises = res.data.list.map(async (item: any) => {
        let content: any = await getContentDetail(item.cid)
        return content
      })
      bannerCases.value = await Promise.all(promises)
    }
  } catch (error) {
    console.error('获取案例列表失败:', error)
  }
}

const getCaseList = async (page: number = 1) => {
  try {
    const params = {
      category: 'case',
      status: 'publish',
      limit: 3,
      page: page
    }
    const res: any = await contentListApi(params)
    if (res.code === 0 && res.data && res.data.list) {
      totalPages.value = Math.ceil(res.data.total/params.limit)
      let promises = res.data.list.map(async (item: any) => {
        let content: any = await getContentDetail(item.cid)
        return content
      })
      caseList.value = await Promise.all(promises)
    }
  } catch (error) {
    console.error('获取案例列表失败:', error)
  }
}

const getContentDetail = (cid: string): Promise<any> => {
	return new Promise((resolve) => {
		contentDetailApi(cid, 'display').then((res: any) => {
			if(res.code === 0) {
				resolve(res.data)
			} else {
				resolve({})
			}
		}).catch(() => {
			resolve({})
		})
	})
}

const changeBannerIndex = (offset: number) => {
  currentBannerIndex.value = (currentBannerIndex.value + offset + bannerCases.value.length) % bannerCases.value.length
  console.log(currentBannerIndex.value)
}

const handlePrevPage = () => {
  if (currentPage.value > 1) {
    getCaseList(--currentPage.value)
  }
}

const handleNextPage = () => {
  if (currentPage.value < totalPages.value) {
    getCaseList(++currentPage.value)
  }
}

const goToBannerDetail = () => {
  if (currentCase.value && currentCase.value.cid) {
    router.push({
      path: '/cases/detail', // 修改路径，去掉 /layout
      query: {
        cid: currentCase.value.cid
      }
    })
  }
}

onMounted(() => {
  getBannerCases().then(() => {
    // 确保有数据后再开始轮播
    if (bannerCases.value.length > 0) {
      startAutoPlay()
    }
  })
  getCaseList()
})

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  stopAutoPlay()
})
</script>

<style scoped>
/* 可以添加一些自定义样式 */
.banner-transition {
  transition: all 0.5s ease-in-out;
}

:deep(.arco-picker-container) {
  border-radius: 0 0 20px 20px;
}
</style>
